#include "qavcodeccontext.h"
#include <QDebug>

#include<QIODevice>

QAVCodecContext::QAVCodecContext(AVCodecContext *ctx, CodecType type, QObject *parent): QObject (parent), m_ctx(ctx), m_type(type)
{
}

QAVCodecContext::~QAVCodecContext()
{
    avcodec_free_context(&m_ctx);
}

void QAVCodecContext::setPictureSize(int w, int h)
{
    m_ctx->width = w;
    m_ctx->height = h;
}

void QAVCodecContext::setTimeBase(AVRational &rational)
{
    m_ctx->time_base = rational;
}

void QAVCodecContext::setTimeBase(int num, int den)
{
    AVRational ration = {num, den};
    setTimeBase(ration);
}

void QAVCodecContext::setFramerate(AVRational &rational)
{
    m_ctx->framerate = rational;
}

void QAVCodecContext::setFramerate(int num, int den)
{
    AVRational ration = {num, den};
    setFramerate(ration);
}

void QAVCodecContext::setMaxBFrames(int number)
{
    m_ctx->max_b_frames = number;
}

void QAVCodecContext::setPixFmt(AVPixelFormat format)
{
    m_ctx->pix_fmt = format;
}

void QAVCodecContext::setOpt(const char *name, const char *val, int search_flags)
{
    av_opt_set(m_ctx->priv_data, name, val, search_flags);
}

void QAVCodecContext::setOpt(const QString &name, QString &val, int search_flags)
{
    this->setOpt(name.toLocal8Bit().data(), val.toLocal8Bit().data(), search_flags);
}

int QAVCodecContext::open2(const AVCodec *codec, AVDictionary **options)
{
    return avcodec_open2(m_ctx, codec, options);
}

int QAVCodecContext::sendFrame(const AVFrame *frame)
{
    return avcodec_send_frame(m_ctx, frame);
}

int QAVCodecContext::sendFrame(const QAVFrame *frame)
{
    return avcodec_send_frame(m_ctx, frame->data());
}

int QAVCodecContext::receivePacket(AVPacket *avpkt)
{
    return avcodec_receive_packet(m_ctx, avpkt);
}

// 需要自行delete
QAVCodecContext* QAVCodecContext::fromEncoderId(enum AVCodecID id, QObject *parent)
{
    AVCodec* codec = avcodec_find_encoder(id);
    if(!codec)
    {
        return nullptr;
    }

    AVCodecContext* ctx = avcodec_alloc_context3(codec);
    if(!ctx)
    {
        return nullptr;
    }
    return new QAVCodecContext(ctx, Encoder, parent);
}

// 需要自行delete
QAVCodecContext* QAVCodecContext::fromEncoderName(const QString &name, QObject *parent)
{
    AVCodec* codec = avcodec_find_encoder_by_name(name.toLocal8Bit().data());
    if(!codec)
    {
        return nullptr;
    }

    AVCodecContext* ctx = avcodec_alloc_context3(codec);
    if(!ctx)
    {
        return nullptr;
    }
    return new QAVCodecContext(ctx, Encoder, parent);
}
